<?php
namespace app\index\controller;
use app\common\library\Auth;
use think\Controller;
use think\Db;
use think\Session;
use think\Cookie;
use think\Loader;
use dx\api_demo\SmsDemo;
class Sms extends Controller{
    /****
     * Class register           登录验证
     * @package application\index\controller\Sms
    */
     public function send(){
        Loader::import('dx.api_demo.SmsDemo',EXTEND_PATH);
        $tel = input('tel');
        $code = rand(100000,999999);
        $name = input('name');
        $type = Db::name('sms_template')->where(['name'=>$name])->find();
        $template = $type['template'];
        set_time_limit(0);
        $sms = new \SmsDemo();
        $sms->sendSms($tel,$code,$template);
        $token = $this->settoken();   //设置token值
        $ctime = strtotime("+3  minutes");  
        $tokens = Db::name('tokens')->insert([
          'token' => $token,
          'ctime' => $ctime,
          'code'  => $code,
          ]);
        if($tokens){
            $arr = [
               'state'     => 1,
               'token'    =>$token,
               'message'   => "发送成功"
            ];
        }else{
            $arr =[
                'state'     => 0,
                'message'   => "发送失败"
            ];
        }
        
        return json($arr);
    }
    public function verify(){
        $post = input('post.');
        $token = $post['token'];
        $list = $this->checktokens($token); //检查token是否有效
        $code = Db::name('tokens')->where(['token'=>$token])->find();
        if($post['code'] == $code['code']){
            Db::name('tokens')->where(['token'=>$token])->delete();
            if($post['name'] == '登录验证'){
                $mobile_id = Db::name('user')->where(['mobile'=>$post['mobile']])->find();
                if($mobile_id){
                  $arr = [
                   'state'     => 1,
                   'user_id'   =>$mobile_id['id'],
                   'message'   => "成功"
                  ];
                }else{
                  $arr = [
                   'state'     => 10002,
                  ];
                }
                 return json($arr);
            }
            $arr = [
               'state'     => 1,
               'message'   => "成功"
            ];
            
        }else{
            $arr = [
               'state'     => $list,
               'message'   => "失败"
            ];
        }
        return json($arr);
    }
   public static function settoken()   //设置token值的方法
   {
       $str = md5(uniqid(md5(microtime(true)),true));
       $str = sha1($str);
       return $str;
   }
    public static function checktokens($token)  //检查token值的方法
   {
      $list = Db::name('tokens')->field('ctime')->where('token="'.$token.'"')->find();
      if($list){
          if(time()-$list['ctime'] > 0){
             return 10000;
          }
      }
       return 10001;
   } 
}
